package com.springboot.demo.io.netty;

import java.net.InetSocketAddress;

import com.springboot.demo.constant.CommonConstant;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * netty 客户端
 *
 * @author supu
 * @since 2020-11-17 10:52
 **/
public class NettyClient {
    public static void main(String[] args) {
        NettyClient nettyClient = new NettyClient();

        // nettyClient.generalClient();

        nettyClient.nettyClient();
    }

    public void generalClient() {
        System.out.println("client start。。。。。。");

        // 获取 selector
        NioEventLoopGroup selector = new NioEventLoopGroup(1);

        // 客户端
        NioSocketChannel client = new NioSocketChannel();

        // 客户端注册到 selector，epoll_ctl(fd5,add(fd6)
        selector.register(client);

        // reactor 响应式编程，设置事件回调函数
        ChannelPipeline pipeline = client.pipeline();
        pipeline.addLast(new MyInHandler());

        // 连接服务端
        ChannelFuture connect = client.connect(new InetSocketAddress(CommonConstant.LOCALHOST, CommonConstant.LOCAL_PORT));
        try {
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello server".getBytes());

            // 客户端发送数据
            ChannelFuture send = client.writeAndFlush(byteBuf);
            send.sync();

            connect.sync().channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void nettyClient() {
        System.out.println("client start。。。。。。");

        NioEventLoopGroup selector = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture connect = bootstrap.group(selector).channel(NioSocketChannel.class)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
                                pipeline.addLast(new MyInHandler());
                            }
                        }).connect(new InetSocketAddress(CommonConstant.LOCALHOST, CommonConstant.LOCAL_PORT));

        try {

            Channel client = connect.sync().channel();

            ByteBuf byteBuf = Unpooled.copiedBuffer("hello server".getBytes());
            // 客户端发送数据
            ChannelFuture send = client.writeAndFlush(byteBuf);
            send.sync();

            client.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
